directives.directive('chart', ["$rootScope", "tools", 'tmp', "$timeout", "$routeParams", "chartServ", function ($rootScope, tools, tmp, $timeout, $routeParams, chartServ) {
    return {
        restrict: 'E',
        scope: true,
        replace: true,
        link: function (scope, element, attr) {
            var config = scope.config = $rootScope.getChart(attr.moduleid ? Number(attr.moduleid) : Number(attr.tmpid));
            var base = attr.base ? Number(attr.base) : $(element).parent().width();
            var chartIdent = String(Math.random());
            var $container = $(element).parent();
            var $ele = $(element);
            var G2ChartObj = null;
            var resp = null;
            var events = {};

            $ele.find('.echarts-container').attr('id', chartIdent);

            scope.loading = false;
            scope.tipInfo = chartServ.chartTips[config.chartType];

            if (config.chartType == 'StandardPieChart') {
                config.chartType = 'pie';
            }
            if (config.chartType == 'StandardLineChart') {
                config.chartType = 'line';
            }
            if (config.chartType == 'StandardBarChart') {
                config.chartType = 'bar';
            }
            if (config.chartType == 'YCategoryStackBarChart') {
                config.chartType = 'verBar';
            }
            if (config.chartType == 'StandardRadarChart') {
                config.chartType = 'radar';
            }
            if (config.chartType == 'StandardScatterchart') {
                config.chartType = 'scatter';
            }

            if (config.chartType == 'StandAreaStack') {
                config.chartType = 'area';
            }

            if (config.chartType == 'HistogramBarChart') {
                config.chartType = 'histogram';
            }

            if (!config.moduleId) {
                scope.tipShown = true;
            } else {
                scope.tipShown = false;
            }

            // 在全局模式下给config做一个复制
            if (attr.fullscreen == '1') {
                config = scope.config = angular.copy(config);
                config.selected = false;
            }

            if (attr.left) {
                config.left = Number(attr.left);
            }
            if (attr.top) {
                config.top = Number(attr.top);
            }
            if (attr.width) {
                config.width = Number(attr.width);
            }
            if (attr.height) {
                config.height = Number(attr.height);
            }

            // 非移动端模式下才是绝对定位,移动端下增加一个底部margin
            if (!config.mobileMode) {
                $ele.addClass('pa');
            } else {
                $ele.addClass('mb20');
                $ele.addClass('pr');
            }

            config.chartType = config.chartType || attr.type;

            if (config.isDrill) {
                config.filters.layerNum = 0;
                config.filters.downDrillValue = "";
            }

            // 下钻以后返回上一步
            scope.back = function () {
                config.filters.layerNum--;
                config.downDrillValues.length--;
                getChartByModuleId(config.moduleId);
            }

            scope.recover_fields = function (flag) {
                if (flag) {
                    $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', config.dimension, config.dimension2, config.measure, config.measure2, config.classifies, config.chartType,config.distance);
                } else {
                    $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', [], [], [], [], [], config.chartType,config.distance);
                }
            }

            scope.fullScreen = function (e) {
                $rootScope.$broadcast('CHART_FULL_SCREEN_EV', angular.copy(config));
            }

            scope.maxable = false;
            scope.mouseover = function () {
                if (attr.maxable == '0' || !config.moduleId) {
                    return false;
                }
                scope.maxable = true;
            }

            var menus = [
                {
                    name: '修改标题',
                    icon: 'write icon',
                    hide: function () {
                        return !config.moduleId;
                    },
                    fn: function () {
                        if (!config.moduleId) {
                            return;
                        }

                        $rootScope.$broadcast('INPUT_EDIT_EV', config.ctitle, function (content) {
                            config.ctitle = content;
                            config.autoTitle = false;
                        });
                        $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                        ifClearCtx = true;
                    }
                },
                {
                    namefn: function () {
                        return config.isDrill ? '取消下钻' : '层级下钻';
                    },
                    icon: 'arrow circle down icon',
                    hide: function () {
                        var downDrillAble = ['pie', 'bar', 'verBar', 'area'];
                        return config.dimension.length < 2 || !config.moduleId || downDrillAble.indexOf(config.chartType) === -1;
                    },
                    fn: function () {
                        if (!config.isDrill) {
                            config.isDrill = true;
                            config.filters.layerNum = 0;
                            config.filters.downDrillValue = "";
                        } else {
                            config.isDrill = false;
                            delete config.filters.layerNum;
                            delete config.filters.downDrillValue;
                            config.downDrillValues.length = 0;
                        }

                        getChartByModuleId(config.moduleId);
                        $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                        ifClearCtx = true;
                    }
                },
                {
                    name: '增加平均值线',
                    icon: 'write square icon',
                    hide: function () {
                        if (config.chartType != 'bar' && config.measure.length!=1 && config.chartType!='line') {
                            return true;
                        }
                        if (!config.moduleId) {
                            return true;
                        }
                    },
                    fn: function () {
                        if (!config.moduleId) {
                            return;
                        }
                        $rootScope.$broadcast('SET_AS_MEAN_LINE_EV');
                        $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                    }
                },
                {
                    name: '分类',
                    icon: 'block layout icon',
                    hide: function () {
                        if (config.chartType != 'line' && config.chartType != 'bar' && config.chartType != 'verBar' && config.chartType != 'histogram') {
                            return true;
                        }
                        if (!config.moduleId) {
                            return true;
                        }
                    },
                    submenusfn: function () {
                        var dimIds = chartServ.collectDimensionColumnIds(config);
                        var dimensionalitys = [];

                        angular.forEach($rootScope.getDimensionality(), function (dim) {
                            dimensionalitys.push({
                                name: dim.columnDesc,
                                hide: function () {
                                    return dimIds.indexOf(dim.columnId) != -1;
                                },
                                selected: function () {
                                    return config.classifies[0] && (config.classifies[0].columnDesc === dim.columnDesc);
                                },
                                fn: function () {
                                    if (config.classifies[0] && (config.classifies[0].columnDesc === dim.columnDesc)) {
                                        config.classifies.length = 0;
                                        // 通知左边的维度列表更新列表
                                        if (scope.selected) {
                                            $rootScope.$broadcast('RECOVER_CLASSFIES_FIELD', true, dim.columnId);
                                        }
                                        addIbmModuleChart();
                                        return;
                                    }

                                    if (scope.selected) {
                                        $rootScope.$broadcast('RECOVER_CLASSFIES_FIELD', false, dim.columnId);
                                    }
                                    config.classifies[0] = dim;
                                    addIbmModuleChart();
                                }
                            });
                        });
                        return dimensionalitys;
                    }
                },
                {
                    name: '转换为',
                    icon: 'exchange icon',
                    hide: function () {
                        // return !config.moduleId;
                        return true;
                    },
                    submenus: [
                        {
                            name: '饼图',
                            hide: function () {
                                return config.classifies.length || config.chartType == 'pie';
                            },
                            fn: function () {
                                config.chartType = 'pie';
                                addIbmModuleChart();
                            }
                        },
                        {
                            name: '折线图',
                            hide: function () {
                                return config.chartType == 'line';
                            },
                            fn: function () {
                                config.chartType = 'line';
                                addIbmModuleChart();
                            }
                        },
                        {
                            name: '柱状图',
                            hide: function () {
                                return config.chartType == 'bar';
                            },
                            fn: function () {
                                config.chartType = 'bar';
                                addIbmModuleChart();
                            }
                        }
                    ]
                },
                // {
                //     name: '转化为表',
                //     icon: "icon table",
                //     hide: function () {
                //         // return !config.moduleId;
                //         return true;
                //     },
                //     fn: function () {
                //         // 删除chart
                //         chartServ.deleteIbmModuleChartByModuleId(config);
                //         // 添加新的表
                //         $rootScope.$broadcast('ADD_SHEET_EV', "summarytab", {
                //             left: $ele.position().left / base,
                //             top: $ele.position().top / base,
                //             height: $ele.height() / base,
                //             width: $ele.width() / base,
                //             transformChartToTable: true,
                //             originChartType: config.chartType,
                //             dataFieldNames: angular.copy(config.measure),
                //             lineFieldNames: angular.copy(config.dimension)
                //         });
                //     }
                // },
                // {
                //     name: '复制',
                //     icon: 'paste icon',
                //     hide: function () {
                //         return !config.moduleId;
                //     },
                //     fn: function () {
                //
                //     }
                // },
                {
                    name: '下载为',
                    icon: 'download icon',
                    hide: function () {
                        return !config.moduleId;
                    },
                    submenus: [
                        {
                            name: 'JPEG图片',
                            icon: 'file image outline icon',
                            fn: function () {
                                $(element).find('.echarts-container').highcharts().exportChart({
                                    filename: config.ctitle,
                                    type: 'image/base64'
                                });
                            }
                        },
                        {
                            name: 'png图片',
                            icon: 'file image outline icon',
                            fn: function () {
                                $(element).find('.echarts-container').highcharts().exportChart({
                                    filename: 'chart'
                                });
                            }
                        },
                        {
                            name: 'pdf文件',
                            icon: 'file pdf outline icon',
                            fn: function () {
                                $(element).find('.echarts-container').highcharts().exportChart({
                                    filename: 'chart',
                                    type: 'application/pdf'
                                });
                            }
                        }
                    ]
                },
                {
                    name: '清空',
                    icon: 'erase icon',
                    hide: function () {
                        return !config.moduleId;
                    },
                    fn: function () {
                        if (config.moduleId) {
                            $rootScope.$broadcast('CONFIRM_EV', {
                                title: '图清除提醒',
                                content: '图清除之后不可恢复,确定清除吗?',
                                btns: {
                                    yes: {
                                        text: "确定删除",
                                        fn: function () {
                                            config.dimension.length = config.measure.length = config.classifies.length = config.distance = 0;
                                            scope.recover_fields(false);

                                            if (G2ChartObj) {
                                                if(G2ChartObj['width']){
                                                    G2ChartObj.clearOverlays();
                                                } else {
                                                    G2ChartObj.clear();
                                                }
                                                $ele.find('.echarts-container').html('');
                                            }
                                        }
                                    },
                                    no: {
                                        text: '取消',
                                        fn: function () {

                                        }
                                    }
                                }
                            });
                        } else {
                            config.dimension.length = config.measure.length = config.classifies.length = 0;
                            scope.recover_fields(false);

                            if (G2ChartObj) {
                                if(G2ChartObj['width']){
                                    G2ChartObj.clearOverlays();
                                } else {
                                    G2ChartObj.clear();
                                }
                                $ele.find('.echarts-container').html('');
                            }
                        }
                    }
                },
                {
                    name: '删除',
                    icon: 'trash icon',
                    fn: function () {
                        if (config.moduleId) {
                            $rootScope.$broadcast('CONFIRM_EV', {
                                title: '图删除提醒',
                                content: '图表删除之后不可恢复,确定删除吗?',
                                btns: {
                                    yes: {
                                        text: "确定删除",
                                        fn: function () {
                                            chartServ.deleteIbmModuleChartByModuleId(config);
                                        }
                                    },
                                    no: {
                                        text: '取消',
                                        fn: function () {

                                        }
                                    }
                                }
                            });
                        } else {
                            scope.delChart(config.tmpId);
                            // 清空字段
                            $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', [], [],[],[],[], config.chartType,'');
                            $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                            $rootScope.$broadcast('CONFIRM_OFF_EV');
                        }
                    }
                }
            ];

            element[0].addEventListener('contextmenu', function (e) {
                if (e.button == 2) {
                    $rootScope.$broadcast('CONTEXTMENU_EV', e.pageX, e.pageY, menus);
                    e.preventDefault();
                }
                e.stopPropagation();
                return false;
            });

            $ele.css({
                width: config.width <= 1 ? base * config.width + 'px' : config.width + 'px',
                height: config.height <= 1 ? base * config.height + 'px' : config.height + 'px'
            });

            if ($routeParams.type == 'editor' || !$routeParams.type || !scope.previewing) {
                $ele.addClass('border');
            }

            // 初始化
            if (!tools.mobileEnv()) {
                // $ele.css({
                //     top: config.top <= 1 ? base * config.top + 'px' : config.top + 'px',
                //     left: config.left <= 1 ? base * config.left + 'px' : config.left + 'px'
                // });
                $ele.css({
                    top: base * config.top + 'px',
                    left: base * config.left + 'px'
                });
            }

            $ele.on('click', function (e) {
                e.stopPropagation();
            });

            if (base * config.top + $ele.height() > $container.height() - 100) {
                $container.height($container.height() + 150);
            }

            if (config.moduleId) {
                getChartByModuleId(config.moduleId);
            } else {
                $ele.addClass(config.chartType);
            }      　

            // 如果是由表转图,则立即开始生成图
            if (config.transformSheetToChart) {
                addIbmModuleChart();
            }      

            // 监听双Y轴事件
            events.SET_AS_MEAN_LINE_EV_OFF = $rootScope.$on('SET_AS_MEAN_LINE_EV', function (e, fieldId, flag) {
                if (scope.selected) {
                    config.setAsMeanLine = !config.setAsMeanLine;
                    if(!config.setAsMeanLine){
                        menus[2].name ='增加平均值线'
                    } else {
                        menus[2].name = '删除平均值线'
                    }
                    addIbmModuleChart();
                }
            });

           
            //监听平均线事件
            events.SET_AS_SECOND_Y_EV_OFF = $rootScope.$on('SET_AS_SECOND_Y_EV', function (e, fieldId, flag) {
                if (scope.selected) {
                    angular.forEach(config.measure, function (mea) {
                        if (mea.fieldId == fieldId) {
                            mea.setAsSecondY = flag;

                            if (flag) {
                                config.hasSecondY = true;
                            }
                        }
                    });

                    addIbmModuleChart();
                }
            });

            //监听直方图间距增加事件
            events.DISTANCE_ADD_EV_OFF = $rootScope.$on('DISTANCE_ADD_EV', function (e, distance) {
                if (scope.selected) {
                    config.distance = distance;
                    addIbmModuleChart();
                }
            });

            // 监听度量变化事件
            events.MEA_CHANGE_EV_OFF = $rootScope.$on('MEA_CHANGE_EV', function (e, fieldId, meaType) {
                if (scope.selected) {
                    angular.forEach(config.measure, function (dim) {
                        if (dim.fieldId == fieldId) {
                            dim.meaType = meaType;
                        }
                    });
                    addIbmModuleChart();
                }
            });

            // 监听横坐标增加
            events.DIMENSION_ADD_EV_OFF = $rootScope.$on('DIMENSION_ADD_EV', function (e, dimension) {
                if (scope.selected) {
                    config.dimension.push(dimension);
                    addIbmModuleChart();
                }
            });

            // 监听横坐标减少
            events.DIMENSION_REDUCE_EV_OFF = $rootScope.$on('DIMENSION_REDUCE_EV', function (e, columnId) {
                if (scope.selected) {
                    angular.forEach(config.dimension, function (dim, index) {
                        if (dim.columnId == columnId) {
                            config.dimension.splice(index, 1);
                            addIbmModuleChart();
                        }
                    });

                    if (config.dimension.length < 2) {
                        config.isDrill = false;
                        delete config.filters.layerNum;
                        delete config.filters.downDrillValue;
                        config.downDrillValues.length = 0;
                    }

                    // 当没有维度时要把分类字段也清空,这样避免后面起冲突
                    if (config.dimension.length == 0) {
                        config.classifies.length = 0;
                    }

                    if (config.dimension.length == 0 || config.measure.length == 0) {
                        $timeout(function () {
                            config.ctitle = "";
                        }, 0);
                    }
                }
            });

            // 监听横坐标覆盖事件
            events.DIMENSION_RECOVER_EV_OFF = $rootScope.$on('DIMENSION_RECOVER_EV', function (e, dimensions) {
                if (scope.selected) {
                    config.dimension = angular.copy(dimensions);
                    addIbmModuleChart();
                }
            });

            // 监听横坐标2增加
            events.DIMENSION2_ADD_EV_OFF = $rootScope.$on('DIMENSION2_ADD_EV', function (e, dimension) {
                if (scope.selected) {
                    if (config.chartType == 'heatmap' || config.chartType == 'heatmarketmap') {
                        config.dimension2[0] = dimension;
                    } else {
                        config.dimension2.push(dimension);
                    }
                    addIbmModuleChart();
                }
            });

             // 监听横坐标2减少
            events.DIMENSION2_REDUCE_EV_OFF = $rootScope.$on('DIMENSION2_REDUCE_EV', function (e, columnId) {
                if (scope.selected) {
                    angular.forEach(config.dimension2, function (dim, index) {
                        if (dim.columnId == columnId) {
                            config.dimension2.splice(index, 1);
                            addIbmModuleChart();
                        }
                    });

                    if (config.dimension.length < 2) {
                        config.isDrill = false;
                        delete config.filters.layerNum;
                        delete config.filters.downDrillValue;
                        config.downDrillValues.length = 0;
                    }

                    // 当没有维度时要把分类字段也清空,这样避免后面起冲突
                    if (config.dimension.length == 0) {
                        config.classifies.length = 0;
                    }

                    if (config.dimension.length == 0 || config.measure.length == 0) {
                        $timeout(function () {
                            config.ctitle = "";
                        }, 0);
                    }
                }
            });

            // 监听横坐标2覆盖事件
            events.DIMENSION2_RECOVER_EV_OFF = $rootScope.$on('DIMENSION2_RECOVER_EV', function (e, dimensions) {
                if (scope.selected) {
                    config.dimension2 = angular.copy(dimensions);
                    addIbmModuleChart();
                }
            });
           

            // 监听纵坐标增加
            events.MEASURE_ADD_EV_OFF = $rootScope.$on('MEASURE_ADD_EV', function (e, measure) {
                if (scope.selected) {
                    // 饼图只能有一个度量
                    if (config.chartType == 'StandardPieChart') {
                        config.measure[0] = measure;
                    } else {
                        config.measure.push(measure);
                    }
                    addIbmModuleChart();
                }
            });

            // 监听纵坐标减少
            events.MEASURE_REDUCE_EV_OFF = $rootScope.$on('MEASURE_REDUCE_EV', function (e, columnId) {
                if (scope.selected) {
                    angular.forEach(config.measure, function (mea, index) {
                        if (mea.columnId == columnId) {
                            config.measure.splice(index, 1);
                            addIbmModuleChart();
                        }
                    });

                    if (config.dimension.length == 0 || config.measure.length == 0) {
                        $timeout(function () {
                            config.ctitle = "";
                        }, 0);
                    }
                }
            });

            // 监听纵坐标覆盖事件
            events.MEASUREMENT_RECOVER_EV_OFF = $rootScope.$on('MEASUREMENT_RECOVER_EV', function (e, measure) {
                if (scope.selected) {
                    config.measure = angular.copy(measure);
                    addIbmModuleChart();
                }
            });

            // 监听宗坐标2增加
            events.MEASURE2_ADD_EV_OFF = $rootScope.$on('MEASURE2_ADD_EV', function (e, measure) {
                if (scope.selected) {
                    if (config.chartType == 'bubble') {
                        config.measure2[0] = measure;
                    } else {
                        config.measure2.push(measure);
                    }
                    addIbmModuleChart();
                }
            });

            // 监听纵坐标2减少
            events.MEASURE2_REDUCE_EV_OFF = $rootScope.$on('MEASURE2_REDUCE_EV', function (e, columnId) {
                if (scope.selected) {
                    angular.forEach(config.measure2, function (mea, index) {
                        if (mea.columnId == columnId) {
                            config.measure2.splice(index, 1);
                            addIbmModuleChart();
                        }
                    });

                    if (config.dimension.length == 0 || config.measure.length == 0) {
                        $timeout(function () {
                            config.ctitle = "";
                        }, 0);
                    }
                }
            });

            // 监听纵坐标2覆盖事件
            events.MEASUREMENT2_RECOVER_EV_OFF = $rootScope.$on('MEASUREMENT2_RECOVER_EV', function (e, measure) {
                if (scope.selected) {
                    config.measure2 = angular.copy(measure);
                    addIbmModuleChart();
                }
            });

            // 监听主排序事件
            events.MAIN_SORT_EV_OFF = $rootScope.$on('MAIN_SORT_EV', function (e, sortField, sortType) {
                if (scope.selected) {
                    config.filters.sortField = sortField;
                    config.filters.sortType = sortType;
                    getChartByModuleId(config.moduleId);
                }
            });

            // 增加模块
            function addIbmModuleChart () {
                if (!chartServ.chartAvailable(config)) {
                    if (G2ChartObj) {
                        if(G2ChartObj['width']){
                            G2ChartObj.clearOverlays();
                        } else {
                            G2ChartObj.clear();
                        }
                        $ele.addClass(config.chartType);
                        $ele.find('.echarts-container').html('');
                        G2ChartObj = null;
                    }
                    scope.loading = false;
                    scope.tipShown = true;
                    return;
                }

                var dataFieldNames = [];
                var dimensionFieldNames = [];
                var implicationFieldNames = [];

                angular.forEach(config.dimension, function (dim) {
                    if (config.chartType != 'scatter' && config.chartType != 'bubble') {
                        implicationFieldNames.push(dim.meaType + '_' + dim.fieldName);
                    } else {
                        implicationFieldNames.push(dim.fieldName);
                    }
                });

                angular.forEach(config.dimension2, function (dim) {
                    if (config.chartType != 'scatter' && config.chartType != 'bubble') {
                        implicationFieldNames.push(dim.meaType + '_' + dim.fieldName);
                    } else {
                        implicationFieldNames.push(dim.fieldName);
                    }
                });

                angular.forEach(config.measure, function (mea) {
                    if (config.chartType != 'scatter' && config.chartType != 'bubble') {
                        dataFieldNames.push(mea.meaType + '_' + mea.fieldName);
                    } else {
                        dataFieldNames.push(mea.fieldName);
                    }
                });

                angular.forEach(config.measure2, function (mea) {
                    if (config.chartType != 'scatter' && config.chartType != 'bubble') {
                        dataFieldNames.push(mea.meaType + '_' + mea.fieldName);
                    } else {
                        dataFieldNames.push(mea.fieldName);
                    }
                });

                // 分类字段
                angular.forEach(config.classifies, function (cla) {
                    dimensionFieldNames.push(cla.meaType + '_' + cla.fieldName);
                });

                scope.loading = true;
                var chartId = '';
                if(config.chartType == 'histogram') {
                    chartId = 'HistogramBarChart'
                } else if(config.chartType == 'scatter' || config.chartType == 'heatmarketmap') {
                    chartId = 'StandardScatterchart'
                } else {
                    chartId = 'StandardLineChart'
                }
                
                tools.get({
                    url: '/Ibm-Client/addIbmModuleChart.htm',
                    data: {
                        implicationFieldName: implicationFieldNames.join(','),
                        dimensionFieldName: dimensionFieldNames.join(','),
                        dataFieldName: dataFieldNames.join(','),
                        tableType: $routeParams.tableType,
                        chartId: chartId,
                        pageId: $routeParams.id,
                        tbId: $routeParams.tbId,
                        distance:config.distance
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            getChartByModuleId(config.moduleId = resp.value);

                            if (!attr.moduleid) {
                                attr.moduleid = config.moduleId;
                            }
                        }
                    }
                });
            }

            // 获取数据
            function getChartByModuleId (moduleId) {
                scope.loading = true;
                moduleId = moduleId || config.moduleId;

                // 合并筛选条件
                var data = {
                    pageId: $routeParams.id,
                    chartStyle: 'Hchart',
                    moduleId: moduleId,
                    resultSize: 900
                };

                config.filters.downDrillValue = config.downDrillValues.join(',');
                angular.extend(data, config.filters);

                tools.get({
                    url: "/Ibm-Client/getChartDatasByModuleId.htm",
                    data: data,
                    succ: function (resp_) {
                        if (resp_.success) {
                            if (G2ChartObj) {
                                if(G2ChartObj['width']){
                                    G2ChartObj.clearOverlays();
                                } else {
                                    G2ChartObj.clear();
                                }
                                
                                $ele.find('.echarts-container').html('');
                            }

                            config.usingData = resp_.value.datas;
                            config.backupData = angular.copy(resp_.value.datas);
                            G2ChartObj = chartServ.drawAllCharts(config.chartType, config.usingData, config, $ele, chartIdent);

                            if (config.autoTitle) {
                                chartServ.makeTitleForChart(config);
                            }

                            $ele.removeClass(config.chartType);
                            scope.loading = false;
                            scope.tipShown = false;
                            resp = resp_;
                        } else {
                            scope.loading = false;
                            tools.msg('系统繁忙,请稍后再试!');
                        }
                    }
                });
            }

            config.getChartByModuleId = getChartByModuleId;

            // 监听图大小重绘
            events.RESIZE_EV_OFF = $rootScope.$on('RESIZE_EV', function () {
                if (scope.selected) {
                    if(G2ChartObj){
                        if(G2ChartObj['width']){
                            G2ChartObj.clearOverlays();
                        } else {
                            G2ChartObj.clear();
                        }
                    }
                    
                    $ele.find('.echarts-container').html('').width($ele.width()).height($ele.height());

                    G2ChartObj = chartServ.drawAllCharts(config.chartType, resp.value.datas, config, $ele, chartIdent);
                }

            });

            // 保存
            events.SAVE_EV_OFF = $rootScope.$on('SAVE_EV', function () {
                var base = $container.width();

                config.width = $ele.width() / base;
                config.height = $ele.height() / base;
                config.top = $ele.position().top / base;
                config.left = $ele.position().left / base;

                // if (config.width <= 1) {
                //     config.width = $ele.width() / base;
                // }
                // if (config.height <= 1) {
                //     config.height = $ele.height() / base;
                // }
                // if (config.top <= 1) {
                //     config.top = $ele.position().top / base;
                // }
                // if (config.left <= 1) {
                //     config.left = $ele.position().left / base;
                // }
                //
                // console.log("保存:", config.moduleId, base, $ele.position().top, config.top, $ele.position().top);
                config.selected = false;
                config.keydownMode = false;
                config.partionDataShown = false;

                config.startItem = undefined;
                config.endItem = undefined;
                config.startPoint = undefined;
                config.endPoint = undefined;

                config.filters = {
                    sortField: '',
                    sortType: ''
                };
                config.downDrillValues = [];

                delete config.usingData;
                delete config.backupData;

                angular.forEach(config.dimension, function (dim) {
                    for (var i in dim) {
                        if (dim[i] === null) {
                            dim[i] = "";
                        }
                    }
                });
                angular.forEach(config.measure, function (mea) {
                    for (var i in mea) {
                        if (mea[i] === null) {
                            mea[i] = "";
                        }
                    }
                });
                angular.forEach(config.classifies, function (mea) {
                    for (var i in mea) {
                        if (mea[i] === null) {
                            mea[i] = "";
                        }
                    }
                });
            });

            // 筛选组件传来筛选条件
            events.FILTER_EV_OFF = $rootScope.$on('FILTER_EV', function (e, conditionId, value) {
                if (value) {
                    config.filters['condition-' + conditionId] = value;
                } else {
                    config.filters['condition-' + conditionId] = null;
                }
                getChartByModuleId(config.moduleId);
            });

            // 清除筛选条件的事件
            events.FILTER_CLEAR_EV_OFF = $rootScope.$on('FILTER_CLEAR_EV', function (e, conditionId) {
                if (!conditionId)
                    return;

                for (var i in config.filters) {
                    if (i.indexOf(conditionId) != -1) {
                        delete config.filters[i];
                    }
                }

                getChartByModuleId(config.moduleId);
            });

            // 监听取消预览事件
            events.PREVIEW_OFF_EV_OFF = $rootScope.$on('PREVIEW_OFF_EV', function () {

            });

            // 监听预览事件
            events.PREVIEW_EV_OFF = $rootScope.$on('PREVIEW_EV', function () {
                scope.selected = false;
            });

            // 监听到联动事件
            events.LINK_EV_OFF = $rootScope.$on('LINK_EV', function (e, link) {
                if (link.id == config.moduleId) {
                    return;
                }
                if (!link.dimensionValue) {
                    config.filters = {
                        sortField: '',
                        sortType: ''
                    };
                    if (config.isDrill) {
                        config.filters.layerNum = 0;
                        config.filters.downDrillValue = "";
                    }
                    config.downDrillValues.length = 0;
                    getChartByModuleId(config.moduleId);
                    return;
                }
                angular.extend(config.filters, link);
                getChartByModuleId(config.moduleId);
            });

            // 删除事件
            events.DEL_CHART_EV_OFF = $rootScope.$on('DEL_CHART_EV', function (e) {
                chartServ.deleteIbmModuleChartByModuleId(config);
            });

            // 更新chart,因为左侧字段列表的重命名
            events.UPDATE_CHART_EV_OFF = $rootScope.$on('UPDATE_CHART_EV', function (e, columnId, columnDesc) {
                angular.forEach(config.dimension, function (dim) {
                    if (dim.columnId === columnId) {
                        dim.columnDesc = columnDesc;
                        getChartByModuleId(config.moduleId);
                        config.ctitle = "";
                    }
                });
                angular.forEach(config.measure, function (mea) {
                    if (mea.columnId === columnId) {
                        mea.columnDesc = columnDesc;
                        getChartByModuleId(config.moduleId);
                        config.ctitle = "";
                    }
                });
            });

            // 清空数据
            events.CLEAR_DATA_EV_OFF = $rootScope.$on('CLEAR_DATA_EV', function () {
                if (scope.selected) {

                }
            });

            scope.$on('$destroy', function () {
                for (var i in events) {
                    if (i.indexOf('_OFF') != -1) {
                        events[i]();
                    }
                }
            });

            $ele.on('keydown', function (e) {
                if (scope.selected) {
                    if (e.keyCode == 8) {
                    }
                }
            });

            $ele.find('.circle').popup({
                content: chartServ.chartTips[config.chartType],
                position: 'top left'
            });

            $ele.delegate('.mCSB_scrollTools', 'click', function (e) {
                e.stopPropagation();
            });

            config.keydownMode = false;
            config.startItem = null;
            config.endItem = null;
            config.startPoint = null;
            config.endPoint = null;

            var selectContainer = $ele.find('.selectContainer');
            var mousedownfn = function (ev) {
                if (config.selected) {
                    return;
                }

                config.keydownMode = true;
                config.startItem = null;
                config.endItem = null;
                config.startPoint = null;
                config.endPoint = null;
            }
            var mouseupfn = function (ev) {
                if (config.selected || !config.keydownMode) {
                    return;
                }

                if (selectContainer.width() == 0) {
                    return;
                }

                config.keydownMode = false;

                var range_start = 0, range_end = 0;
                if (config.startPoint.x < config.endPoint.x) {
                    for (var i = 0; i < config.usingData.length; i++) {
                        if (config.usingData[i].dimension == config.startItem) {
                            range_start = i;
                            break;
                        }
                    }
                    for (var i = config.usingData.length - 1; i >= 0; i--) {
                        if (config.usingData[i].dimension == config.endItem) {
                            range_end = i;
                            break;
                        }
                    }
                } else {
                    for (var i = 0; i < config.usingData.length; i++) {
                        if (config.usingData[i].dimension == config.startItem) {
                            range_end = i;
                            break;
                        }
                    }
                    for (var i = config.usingData.length - 1; i >= 0; i--) {
                        if (config.usingData[i].dimension == config.endItem) {
                            range_start = i;
                            break;
                        }
                    }
                }
                if(G2ChartObj){
                    if(G2ChartObj['width']){
                        G2ChartObj.clearOverlays();
                    } else {
                        G2ChartObj.clear();
                    }
                }
               
                selectContainer.addClass('none');
                $ele.find('.echarts-container').html('');

                if (range_end >= range_start) {
                    config.usingData = config.usingData.slice(range_start, range_end + 1);
                } else {
                    config.usingData = config.usingData.slice(range_end, range_start + 1);
                }

                G2ChartObj = chartServ.drawAllCharts(config.chartType, config.usingData, config, $ele, chartIdent);
                config.partionDataShown = true;
                selectContainer.width(0);
            }

            config.restoreAllData = function (e) {
                if (config.filters.layerNum) {
                    config.filters.layerNum--;
                    config.downDrillValues.length--;
                    getChartByModuleId(config.moduleId);

                    if (config.filters.layerNum === 0) {
                        config.partionDataShown = false;
                    }
                } else {
                    if(G2ChartObj){
                        if(G2ChartObj['width']){
                            G2ChartObj.clearOverlays();
                        } else {
                            G2ChartObj.clear();
                        }
                    }
                    
                    $ele.find('.echarts-container').html('');
                    config.usingData = angular.copy(config.backupData);
                    G2ChartObj = chartServ.drawAllCharts(config.chartType, config.usingData, config, $ele, chartIdent);
                    config.partionDataShown = false;
                }
                e.stopPropagation();
            }

            config.fff = function (e) {
                e.stopPropagation();
            }

            $ele.on('mouseup', mouseupfn);
            $ele.on('mousedown', mousedownfn);
            $ele.on('click', function () {
                config.keydownMode = false;
            });
        },
        templateUrl: "/trend-new-BI/app/components/common/chartManager/chart/chartView.html"
    }
}]);